﻿/**
 * This is a part of MCServe, which is available under the Apache license 2.0.
 * With this code, you may do whatever you want as long as that is not in conflict with this license.
 * In addition, you should have a reference to the original project to include (http://mcserve.codeplex.com).
 * 
 * Author       : Lars Krämer ( Xe77a )
 * Website      : http://www.lkraemer.de
 * Project      : MCServe (http://mcserve.codeplex.com)
 * Copyright    : Copyright (c) 2013 lkraemer.de
 * License      : http://mcserve.codeplex.com/license
 * Description  : This is a part of the core functionality of the gui
 */

using MCServeAPI;
using MCServeAPI.Types;
using MCServeCore;
using MCServeCore.Components;
using MCServeCore.PlayerObjects;
using MCServeLib;
using MCServeLib.Types;
using Newtonsoft.Json;
using System;
using System.Diagnostics;
using System.IO;
using System.Net;
using System.Threading;
using System.Windows;

namespace MCServe
{
    public partial class MainWindow : Window
    {
        private string MCServeAccountUsernameTextBoxContent = "";
        private string MCServeAccountPasswordTextBoxContent = "";

        public MainWindow()
        {
            InitializeComponent();

            this.Loaded += (s, e) =>
            {
                DWMHelper.EnableGlassEffect(this);
            };

            // Start the Server-Thread
            ServerData.MCServeServer = new GameServer(AppHostTypes.GUI);
            ServerData.ServerThread = new Thread(new ThreadStart(ServerData.MCServeServer.Initialize));
            ServerData.ServerThread.Start();

            Thread.Sleep(2000);

            MCServeAccountUsernameTextBoxContent = "Username";
            MCServeAccountPasswordTextBoxContent = "********";

            MCServeAccount_Notes.AcceptsReturn = true;
            MCServeAccount_Notes.AcceptsTab = true;
            MCServeAccount_Notes.IsReadOnly = true;

            if (File.Exists(GameServer.Paths.Get(MCServePaths.LOG_SERVER)))
            {
                StreamReader LogReader = new StreamReader(GameServer.Paths.Get(MCServePaths.LOG_SERVER));
                MCServeLogsServer.Text = LogReader.ReadToEnd();
                LogReader.Close();
            }
            if (File.Exists(GameServer.Paths.Get(MCServePaths.LOG_MESSAGES)))
            {
                StreamReader LogReader = new StreamReader(GameServer.Paths.Get(MCServePaths.LOG_MESSAGES));
                MCServeLogsMessages.Text = LogReader.ReadToEnd();
                LogReader.Close();
            }
            if (File.Exists(GameServer.Paths.Get(MCServePaths.LOG_WARNING)))
            {
                StreamReader LogReader = new StreamReader(GameServer.Paths.Get(MCServePaths.LOG_WARNING));
                MCServeLogsWarning.Text = LogReader.ReadToEnd();
                LogReader.Close();
            }
            if (File.Exists(GameServer.Paths.Get(MCServePaths.LOG_ERRORS)))
            {
                StreamReader LogReader = new StreamReader(GameServer.Paths.Get(MCServePaths.LOG_ERRORS));
                MCServeLogsErrors.Text = LogReader.ReadToEnd();
                LogReader.Close();
            }

            this.ConsoleTextArea.DataContext = GameServer.Console;
            this.ListPlayerArea.ItemsSource = GameServer.PlayerList.Players;
            this.MCServePropertiesList_MinecraftProperties.ItemsSource = GameServer.ServerProperties.Properties;

            this.MCServePropertiesList_BannedIp.ItemsSource = GameServer.BannedIps.Ips;
            this.MCServePropertiesList_BannedPlayer.ItemsSource = GameServer.BannedPlayers.Players;
            this.MCServePropertiesList_WhiteListPlayer.ItemsSource = GameServer.WhiteList.Players;
            this.MCServePropertiesList_OpPlayer.ItemsSource = GameServer.Ops.Players;

            // Load the server data
            MCServe.Init.LoadData.LoadServerData();

            #region # Set the server-data #

            // About MCServe
            this.AboutLabelVersionGui.Content = "v" + MCServe.Meta.Version.Major.ToString() + "." + MCServe.Meta.Version.Minor.ToString() + "." + MCServe.Meta.Version.Update.ToString() + " (" + MCServe.Meta.Release.ToString() + ")";
            this.AboutLabelVersionServer.Content = "v" + MCServeCore.Meta.Version.Major.ToString() + "." + MCServeCore.Meta.Version.Minor.ToString() + "." + MCServeCore.Meta.Version.Update.ToString() + " (" + MCServeCore.Meta.Release.ToString() + ")";
            this.AboutLabelVersionApi.Content = "v" + MCServeAPI.Meta.Version.Major.ToString() + "." + MCServeAPI.Meta.Version.Minor.ToString() + "." + MCServeAPI.Meta.Version.Update.ToString() + " (" + MCServeAPI.Meta.Release.ToString() + ")";
            this.AboutLabelVersionLibrary.Content = "v" + MCServeLib.Meta.Version.Major.ToString() + "." + MCServeLib.Meta.Version.Minor.ToString() + "." + MCServeLib.Meta.Version.Update.ToString() + " (" + MCServeLib.Meta.Release.ToString() + ")";
            this.AboutLabelVersionUpdateManager.Content = "v" + MCServeUpdate.Meta.Version.Major.ToString() + "." + MCServeUpdate.Meta.Version.Minor.ToString() + "." + MCServeUpdate.Meta.Version.Update.ToString() + " (" + MCServeUpdate.Meta.Release.ToString() + ")";
            //this.AboutLabelMCServePropertiesVersion.Content = GameServer.ServerProperties.MCServePropertiesVersion.ToString();

            #endregion

            GameServer.Console.SendMessage("MCServe is ready to use", ServerConsole.OutputTarget.MessageLogAndConsole, ServerConsole.OutputTypes.Information);
        }

        private void MCServeDashboard_ServerStartStop(object sender, RoutedEventArgs e)
        {
            /**
             * Start / Stop the Server-Thread
             */
            if (ServerData.MCServeServer.IsRunning)
            {
                if (ServerData.MCServeServer.SetState(false))
                    this.MCServeDashboardButton_ServerStartStop.Content = "Start";
            }
            else
            {
                if (ServerData.MCServeServer.SetState(true))
                    this.MCServeDashboardButton_ServerStartStop.Content = "Stop";
            }
        }

        private void MCServePropertiesRemoveButton_OpPlayer_Click(object sender, RoutedEventArgs e)
        {
            if (this.MCServePropertiesList_OpPlayer.Items.IndexOf(this.MCServePropertiesList_OpPlayer.SelectedItem) >= 0)
            {
                Player pl = (Player)this.MCServePropertiesList_OpPlayer.Items.GetItemAt(this.MCServePropertiesList_OpPlayer.Items.IndexOf(this.MCServePropertiesList_OpPlayer.SelectedItem));
                GameServer.Ops.Remove(pl.Name);
            }
        }

        private void MCServePropertiesRemoveButton_WhiteListPlayer_Click(object sender, RoutedEventArgs e)
        {
            if (this.MCServePropertiesList_WhiteListPlayer.Items.IndexOf(this.MCServePropertiesList_WhiteListPlayer.SelectedItem) >= 0)
            {
                Player pl = (Player)this.MCServePropertiesList_WhiteListPlayer.Items.GetItemAt(this.MCServePropertiesList_WhiteListPlayer.Items.IndexOf(this.MCServePropertiesList_WhiteListPlayer.SelectedItem));
                GameServer.WhiteList.Remove(pl.Name);
            }
        }

        private void MCServePropertiesRemoveButton_BannedPlayer_Click(object sender, RoutedEventArgs e)
        {
            if (this.MCServePropertiesList_BannedPlayer.Items.IndexOf(this.MCServePropertiesList_BannedPlayer.SelectedItem) >= 0)
            {
                Player pl = (Player)this.MCServePropertiesList_BannedPlayer.Items.GetItemAt(this.MCServePropertiesList_BannedPlayer.Items.IndexOf(this.MCServePropertiesList_BannedPlayer.SelectedItem));
                GameServer.BannedPlayers.Remove(pl.Name);
            }
        }

        private void MCServePropertiesRemoveButton_BannedIp_Click(object sender, RoutedEventArgs e)
        {
            if (this.MCServePropertiesList_BannedIp.Items.IndexOf(this.MCServePropertiesList_BannedIp.SelectedItem) >= 0)
            {
                IpObject ip = (IpObject)this.MCServePropertiesList_BannedIp.Items.GetItemAt(this.MCServePropertiesList_BannedIp.Items.IndexOf(this.MCServePropertiesList_BannedIp.SelectedItem));
                GameServer.BannedIps.Remove(ip);
            }
        }

        private void MCServePropertiesAddButton_OpPlayer_Click(object sender, RoutedEventArgs e)
        {
            Player pl = new Player();
            pl.Name = this.MCServePropertiesTextBox_OpPlayer.Text;
            GameServer.Ops.Add(pl);

            this.MCServePropertiesTextBox_OpPlayer.Text = "";
        }

        private void MCServePropertiesAddButton_WhiteListPlayer_Click(object sender, RoutedEventArgs e)
        {
            GameServer.WhiteList.Add(this.MCServePropertiesTextBox_WhiteListPlayer.Text);

            this.MCServePropertiesTextBox_WhiteListPlayer.Text = "";
        }

        private void MCServePropertiesAddButton_BannedPlayer_Click(object sender, RoutedEventArgs e)
        {
            Player pl = new Player();
            pl.Name = this.MCServePropertiesTextBox_BannedPlayer.Text;
            GameServer.BannedPlayers.Add(pl);

            this.MCServePropertiesTextBox_BannedPlayer.Text = "";
        }

        private void MCServePropertiesAddButton_BannedIp_Click(object sender, RoutedEventArgs e)
        {
            IpObject ip = new IpObject(this.MCServePropertiesTextBox_BannedIp.Text);
            GameServer.BannedIps.Add(ip);

            this.MCServePropertiesTextBox_BannedIp.Text = "";
        }

        private void MCServeDashboard_MessageSend(object sender, RoutedEventArgs e)
        {
            /**
             * Sends the content to the serverconsole
             */
            if (this.MessageTextArea.Text[0] == '/')
            {
                GameServer.Console.SendMessage(this.MessageTextArea.Text, ServerConsole.OutputTarget.Console, ServerConsole.OutputTypes.Command);
            }
            else
            {
                GameServer.Console.SendMessage(this.MessageTextArea.Text, ServerConsole.OutputTarget.MessageLogAndConsole, ServerConsole.OutputTypes.Message);
            }
            this.MessageTextArea.Text = "";
        }

        private void MCServeDashboard_MessageKeyEvent(object sender, System.Windows.Input.KeyEventArgs e)
        {
            /**
             * Sends the content to the serverconsole
             */
            if (e.Key == System.Windows.Input.Key.Enter)
            {
                if (this.MessageTextArea.Text[0] == '/')
                {
                    GameServer.Console.SendMessage(this.MessageTextArea.Text, ServerConsole.OutputTarget.Console, ServerConsole.OutputTypes.Command);
                }
                else
                {
                    GameServer.Console.SendMessage(this.MessageTextArea.Text, ServerConsole.OutputTarget.MessageLogAndConsole, ServerConsole.OutputTypes.Message);
                }
                this.MessageTextArea.Text = "";
            }
        }

        private void Window_Closed_1(object sender, EventArgs e)
        {
            ServerData.MCServeServer.SetState(false);
        }

        private void MCServeAccount_Register(object sender, RoutedEventArgs e)
        {
            Process.Start(MCServeLib.MCServeSites.LOGIN + "/Account/Register");
        }

        private void MCServeAccount_Login(object sender, RoutedEventArgs e)
        {
            MCServeAccount_LoginProgress.Visibility = System.Windows.Visibility.Visible;

            ApiRequest AccountLogin = new ApiRequest();
            AccountLogin.ApiAction = ApiActions.ACCOUNTLOGINASDEVICE;
            AccountLogin.AddValue(ApiValues.AccountUsername, MCServeAccount_Username.Text);
            AccountLogin.AddValue(ApiValues.AccountPassword, StringFunctions.GetMD5Hash(MCServeAccount_Password.Password));
            AccountLogin.AddValue(ApiValues.DeviceType, DeviceTypes.WindowsClient);
            AccountLogin.RequestHandle = new DownloadStringCompletedEventHandler(AccountLoginHandle);
            AccountLogin.Send();
        }

        void AccountLoginHandle(object sender, DownloadStringCompletedEventArgs e)
        {
            JsonObjectAccountDeviceLoginResult LoadedUserData = JsonConvert.DeserializeObject<JsonObjectAccountDeviceLoginResult>(e.Result);

            if (!LoadedUserData.Result)
            {
                MessageBox.Show(LoadedUserData.Message.Message, "Warnung");
            }
            else
            {
                MCServeGuiContentTabs.SelectedItem = MainWindowTab_MCServeAccountOverview;
                MainWindowTab_MCServeAccountOverview.Visibility = System.Windows.Visibility.Visible;
                MainWindowTab_MCServeAccountLogin.Visibility = System.Windows.Visibility.Collapsed;
            }

            MCServeAccount_LoginProgress.Visibility = System.Windows.Visibility.Collapsed;
        }

        private void ListPlayerArea_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
        {
            MCServeCore.PlayerObjects.Player SelectedPlayer = (MCServeCore.PlayerObjects.Player)ListPlayerArea.SelectedItem;

            switch (SelectedPlayer.Type)
            {
                case MCServeCore.PlayerObjects.PlayerType.ADMINISTRATOR:
                    {
                        MCServeDashboard_ButtonPlayerBan.IsEnabled = false;
                        MCServeDashboard_ButtonPlayerKick.IsEnabled = false;
                        MCServeDashboard_ButtonPlayerGamemode.IsEnabled = true;
                        MCServeDashboard_ButtonPlayerGiveItem.IsEnabled = true;
                    } break;
                case MCServeCore.PlayerObjects.PlayerType.GUEST:
                    {
                        MCServeDashboard_ButtonPlayerBan.IsEnabled = true;
                        MCServeDashboard_ButtonPlayerKick.IsEnabled = true;
                        MCServeDashboard_ButtonPlayerGamemode.IsEnabled = true;
                        MCServeDashboard_ButtonPlayerGiveItem.IsEnabled = true;
                    } break;
                case MCServeCore.PlayerObjects.PlayerType.MEMBER:
                    {
                        MCServeDashboard_ButtonPlayerBan.IsEnabled = true;
                        MCServeDashboard_ButtonPlayerKick.IsEnabled = true;
                        MCServeDashboard_ButtonPlayerGamemode.IsEnabled = true;
                        MCServeDashboard_ButtonPlayerGiveItem.IsEnabled = true;
                    } break;
                case MCServeCore.PlayerObjects.PlayerType.MODERATOR:
                    {
                        MCServeDashboard_ButtonPlayerBan.IsEnabled = true;
                        MCServeDashboard_ButtonPlayerKick.IsEnabled = true;
                        MCServeDashboard_ButtonPlayerGamemode.IsEnabled = true;
                        MCServeDashboard_ButtonPlayerGiveItem.IsEnabled = true;
                    } break;
                case MCServeCore.PlayerObjects.PlayerType.SERVER:
                    {
                        MCServeDashboard_ButtonPlayerBan.IsEnabled = false;
                        MCServeDashboard_ButtonPlayerKick.IsEnabled = false;
                        MCServeDashboard_ButtonPlayerGamemode.IsEnabled = true;
                        MCServeDashboard_ButtonPlayerGiveItem.IsEnabled = false;
                    } break;
                default: {
                    MessageBox.Show("Unknown Error");
                } break;
            }
        }
        private void MCServeAccountUsername_TextBoxGotFocus(object sender, RoutedEventArgs e)
        {
            if (MCServeAccount_Username.Text == MCServeAccountUsernameTextBoxContent)
            {
                MCServeAccount_Username.Text = "";
            }
        }
        private void MCServeAccountPassword_TextBoxGotFocus(object sender, RoutedEventArgs e)
        {
            if (MCServeAccount_Password.Password == MCServeAccountPasswordTextBoxContent)
            {
                MCServeAccount_Password.Password = "";
            }
        }
        private void MCServeAccountUsername_TextBoxLostFocus(object sender, RoutedEventArgs e)
        {
            if (MCServeAccount_Username.Text == "")
            {
                MCServeAccount_Username.Text = MCServeAccountUsernameTextBoxContent;
            }
        }
        private void MCServeAccountPassword_TextBoxLostFocus(object sender, RoutedEventArgs e)
        {
            if (MCServeAccount_Password.Password == "")
            {
                MCServeAccount_Password.Password = MCServeAccountPasswordTextBoxContent;
            }
        }

        private void MCServePropertiesList_SelectionChanged(object sender, RoutedEventArgs e)
        {
            MessageBox.Show("Hier soll sich ein kleines Fenster öffnen, indem die jew. Variable bearbeitet werden kann.");
        }

        private void MCServeDashboard_ServerRestart(object sender, RoutedEventArgs e)
        {

        }

        private void MCServeDashboard_ServerReload(object sender, RoutedEventArgs e)
        {
        }
    }
}
